package org.ala.tcp_feign_server.context.executor;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 执行线程池
 *
 * @author 骆毅(ala)
 * @date 2024年4月20日
 */
public class TcpFeignServerExecutorThreadPool {

	
	/**
	 * 公共线程池
	 */
	protected ThreadPoolExecutor common;
	/**
	 * 先初始化在开netty，可以理解为运行时threadPoolMapper是只读的
	 */
	protected Map<Object, ThreadPoolExecutor> threadPoolMapper = new HashMap<>();
	/**
	 * 
	 */
	protected ThreadPoolExecutor COMMON;
	
	
	public TcpFeignServerExecutorThreadPool(int coreSize, int maxSize, int queueSize) {
		//	创建公共线程池
		ThreadPoolExecutor pool = initThreadPool(coreSize, maxSize, queueSize, "Common");
		COMMON = pool;
	}
	
	
	/**
	 * 取bean的执行线程池
	 */
	public ThreadPoolExecutor getExecutorThreadPool(Object bean) {
		ThreadPoolExecutor pool = threadPoolMapper.get(bean);
		if (pool == null) {return COMMON;}
		else {return pool;}
	}
	
	
	/**
	 * 给bean创建私有线程池
	 */
	public void createDedicated(Object bean, int coreSize, int maxSize, int queueSize) {
		String prefix = bean.getClass().getSimpleName();
		ThreadPoolExecutor pool = initThreadPool(coreSize, maxSize, queueSize, prefix);
		threadPoolMapper.put(bean, pool);
	}
	
	
	/**
	 * 初始化线程池
	 */
	protected ThreadPoolExecutor initThreadPool(int coreSize, int maxSize, int queueSize, String prefix) {
		ThreadPoolExecutor pool = new ThreadPoolExecutor(
					coreSize, maxSize,
					180, TimeUnit.SECONDS,
					new ArrayBlockingQueue<>(queueSize),
					new ThreadFactory() {
						AtomicInteger count = new AtomicInteger(0);
						public Thread newThread(Runnable r) {
							Thread t = new Thread(r);
							t.setName(prefix + "_thread_" + count.getAndIncrement());
							return t;
						}
					}
				);
		return pool;
	}
	
}
